package edu.dayu.config;

import edu.dayu.constant.MqConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MQConfig {

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    DirectExchange test1Exchange(){
        return new DirectExchange(MqConstant.EXCHANGE_DIRECT_TEST1,true,false);
    }

    @Bean
    public Queue test1Queue() {
        // durable: 是否持久化,默认是false,持久化队列：会被存储在磁盘上，当消息代理重启时仍然存在，暂存队列：当前连接有效
        // exclusive: 默认也是false，只能被当前创建的连接使用，而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete: 是否自动删除，当没有生产者或者消费者使用此队列，该队列会自动删除。
        return new Queue(MqConstant.QUEUE_TEST1, true, false, false);
    }

    @Bean
    Binding test1RouteBinding() {
        return BindingBuilder.bind(test1Queue()).to(test1Exchange()).with(MqConstant.ROUTING_TEST1);
    }


    @Bean
    DirectExchange test2Exchange(){
        return new DirectExchange(MqConstant.EXCHANGE_DIRECT_TEST2,true,false);
    }

    @Bean
    public Queue test2Queue() {
        Map<String, Object> map = new HashMap<>();
        // 绑定该队列到私信交换机
        map.put("x-dead-letter-exchange", MqConstant.EXCHANGE_DEAD_TEST3);
        map.put("x-dead-letter-routing-key", MqConstant.ROUTING_TEST3);
        // 6s 过期
        map.put("x-message-ttl", 6 * 1000);
        return new Queue(MqConstant.QUEUE_TEST2, true, false, false,map);
    }

    @Bean
    Binding test2RouteBinding() {
        return BindingBuilder.bind(test2Queue()).to(test2Exchange()).with(MqConstant.ROUTING_TEST2);
    }


    @Bean
    DirectExchange test3Exchange(){
        return new DirectExchange(MqConstant.EXCHANGE_DEAD_TEST3,true,false);
    }

    @Bean
    public Queue test3Queue() {
        return new Queue(MqConstant.QUEUE_TEST3, true, false, false);
    }

    @Bean
    Binding test3RouteBinding() {
        return BindingBuilder.bind(test3Queue()).to(test3Exchange()).with(MqConstant.ROUTING_TEST3);
    }


}
